using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SunshineFarmWord
{
    // 角色跑到物体后方将物体变透明
    public class GameObjTransparent : MonoBehaviour
    {
        public class SpriteRendererData
        {
            public string layerName;
            public float alpha;
        }


        [field: SerializeField]
        public SpriteRenderer[] spriteRendererArr;
        //透明度
        private float _alpha = 0.5f;
        // 角色之上层名字
        private string AboveLayerName = "PlayerUp";
        //存储
        private Dictionary<int, SpriteRendererData> _spriteRendererDic = new Dictionary<int, SpriteRendererData>();
        void Start()
        {
            InitSpriteData();
        }

        private void InitSpriteData()
        {
            if (spriteRendererArr.Length != 0) return;

            bool isTrue = TryGetComponent(out SpriteRenderer spriteRenderer);
            if (isTrue)
            {
                spriteRendererArr = new SpriteRenderer[1];
                spriteRendererArr[0] = spriteRenderer;
            }
        }

        void OnTriggerEnter2D(Collider2D other)
        {
            if (other.CompareTag(PlayerStateReusableData.Collider2DTagEnum.Player.ToString()))
            {
                for (int i = 0; i < spriteRendererArr.Length; i++)
                {
                    SpriteRenderer spriteRenderer = spriteRendererArr[i];

                    if (!_spriteRendererDic.ContainsKey(i))
                    {
                        SpriteRendererData data = new SpriteRendererData();
                        data.alpha = spriteRenderer.color.a;
                        data.layerName = spriteRenderer.sortingLayerName;
                        _spriteRendererDic.Add(i, data);
                    }

                    //
                    spriteRenderer.color = new Color(spriteRenderer.color.r, spriteRenderer.color.g, spriteRenderer.color.b, _alpha);
                    spriteRenderer.sortingLayerName = AboveLayerName;
                }
            }
        }

        void OnTriggerExit2D(Collider2D other)
        {
            if (other.CompareTag(PlayerStateReusableData.Collider2DTagEnum.Player.ToString()))
            {
                for (int i = 0; i < spriteRendererArr.Length; i++)
                {
                    SpriteRenderer spriteRenderer = spriteRendererArr[i];
                    //
                    bool isValue = _spriteRendererDic.TryGetValue(i, out SpriteRendererData data);
                    if (isValue)
                    {
                        spriteRenderer.color = new Color(spriteRenderer.color.r, spriteRenderer.color.g, spriteRenderer.color.b, data.alpha);
                        spriteRenderer.sortingLayerName = data.layerName;
                    }
                }
            }
        }
    }
}
